'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 每日任务
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var dataApi = require('../../../libs/dataApi');
var rewardService = require('../../../services/rewardService');
var dailyService = require('../../../services/dailyService');
var dailyConf = require('../../../config/dailyConf');
var roleService = require('../../../services/roleService');
var taskService = require('../../../services/taskService.js');
var PlayerManager = require('../../../libs/playerManager');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 获取任务奖励
 */
Handler.prototype.reward = function (msg, session, next) {
    var role_id = session.uid;
    var daily_task_id = msg.daily_task_id;
    if (!daily_task_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var daily_reward_gold;
    var daily_reward_exp;
    var add_active = 0;
    var reward_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'arena', 'expedition', 'bag', 'skill', 'build', 'soldier', 'task', 'achieve', 'daily_task', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var daily_task_model = player_manager.daily_task;

                if (!daily_task_model.rewardTask(daily_task_id)) {
                    return next(null, {
                        code: Code.TASK_REWARD_ERROR
                    });
                }

                var daily_conf = dataApi.daily.findById(daily_task_id);
                if (!daily_conf) {
                    return next(null, {
                        code: Code.TASK_NOT_SAVE
                    });
                }

                var hero_lv = role_model.getLv();

                var state = hero_lv >= daily_conf.player_level_min && hero_lv <= daily_conf.player_level_max;
                if (!state) {
                    return next(null, {
                        code: Code.TASK_NOT_LV
                    });
                }
                reward_list = dailyService.getRewardList(daily_task_id);
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_DAILY_TASK, operationType.OPR_ACT_DAILY_TASK_REWARD);

                daily_reward_gold = dailyConf.getGoldReward(daily_task_id, role_model.getLv());
                daily_reward_exp = dailyConf.getExpReward(daily_task_id, role_model.getLv());
                roleService.addExp(player_manager, daily_reward_exp);
                roleService.addGoldLimit(player_manager, moduleType.MDL_ACT_DAILY_TASK, operationType.OPR_ACT_DAILY_TASK_REWARD, daily_reward_gold);

                // 加入任务id对应活跃度 到数据库
                add_active = dailyConf.getDailyTaskActive(daily_task_id) || 0;
                daily_task_model.addDailyActive(add_active);

                // 任务完成次数统计
                taskService.addCompleteEverydayNum(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    gold: daily_reward_gold,
                    exp: daily_reward_exp,
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 领取每日完成任务活跃度
 */
Handler.prototype.receiveDailyActive = function (msg, session, next) {
    var role_id = session.uid;
    var active_id = msg.active_id;
    if (!active_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var reward_list;
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'arena', 'expedition', 'task', 'achieve', 'daily_task', 'bag', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var daily_task_model = player_manager.daily_task;

                // 是否领取过
                if (!daily_task_model.isActiveReceive(active_id)) {
                    return next(null, {
                        code: Code.TASK_REWARD_ACTIVE_ERROR
                    });
                }

                // 增加已领取活跃度ID
                daily_task_model.addReceiveActiveId(active_id);

                // 发送活跃奖励到玩家背包
                reward_list = dailyConf.getActiveRewardList(active_id);
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_DAILY_TASK, operationType.OPR_ACT_DAILY_TASK_ACTIVE_REWARD, active_id);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 领取每日月卡钻石接口
 */
Handler.prototype.receiveMonthDay = function (msg, session, next) {
    var role_id = session.uid;
    var daily_task_id = msg.daily_task_id;
    if (!daily_task_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var reward_itm = {};
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'task', 'arena', 'expedition', 'achieve', 'daily_task', 'pay', 'bag', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var daily_task_model = player_manager.daily_task;
                var pay_model = player_manager.pay;

                // 是否为月卡用户
                if (!pay_model.isMonthDay()) {
                    return next(null, {
                        code: Code.MONTHDAY_USER_NOT
                    });
                }

                // 是否领取过
                if (daily_task_model.getScheduleTaskState(daily_task_id) !== 0) {
                    return next(null, {
                        code: Code.TASK_HAVE
                    });
                }

                // 增加月卡领取状态
                daily_task_model.addScheduleTaskState(daily_task_id);

                // 发送活跃奖励到玩家背包
                reward_itm = dailyConf.getRewardList(daily_task_id);
                rewardService.addRewardToRole(player_manager, reward_itm, moduleType.MDL_ACT_MONTH_CARD, operationType.OPR_ACT_MONTH_CARD_DAILY_REWARD);

                // 移除任务
                if (daily_task_model.getScheduleTaskState(daily_task_id) == 1) {
                    daily_task_model.removeTask(daily_task_id);
                }

                // 加入任务id对应活跃度 到数据库
                var add_active = dailyConf.getDailyTaskActive(daily_task_id) || 0;
                daily_task_model.addDailyActive(add_active);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: [reward_itm]
                }
            });
        }
    );
};

/**
 * 领取每日时间点体力任务奖励接口
 */
Handler.prototype.receiveEnergy = function (msg, session, next) {
    var role_id = session.uid;
    var daily_task_id = msg.daily_task_id;
    if (!daily_task_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var reward_itm = {};
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'task', 'achieve', 'daily_task', 'bag', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var daily_task_model = player_manager.daily_task;

                // 是否在领取时间内
                var daily_conf = dailyConf.getRewardList(daily_task_id);
                var total_delay_time = daily_conf.finish_time + 300;
                var time_poor = moment().startOf('day').add(daily_conf.start_time, 's') <= moment() && moment().startOf('day').add(total_delay_time, 's') >= moment();
                if (!time_poor) {
                    return next(null, {
                        code: Code.TASK_DAILY_TIME_ENERGY
                    });
                }

                // 是否领取过
                if (daily_task_model.getScheduleTaskState(daily_task_id) !== 0) {
                    return next(null, {
                        code: Code.TASK_HAVE
                    });
                }

                // 增加任务领取状态
                daily_task_model.addScheduleTaskState(daily_task_id);

                // 发送活跃奖励到玩家背包
                reward_itm = dailyConf.getRewardList(daily_task_id);
                rewardService.addRewardToRole(player_manager, reward_itm, moduleType.MDL_ACT_TIMING_ENERGY, operationType.OPR_ACT_TIMING_ENERGY_REWARD);

                // 移除任务
                if (daily_task_model.getScheduleTaskState(daily_task_id) == 1) {
                    daily_task_model.removeTask(daily_task_id);
                }

                // 加入任务id对应活跃度 到数据库
                var add_active = dailyConf.getDailyTaskActive(daily_task_id) || 0;
                daily_task_model.addDailyActive(add_active);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: [reward_itm]
                }
            });
        }
    );
};

/**
 * 领取每日至尊卡送钻石接口
 */
Handler.prototype.receiveExtreme = function (msg, session, next) {
    var role_id = session.uid;
    var daily_task_id = msg.daily_task_id;
    if (!daily_task_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var reward_itm = {};
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'task', 'achieve', 'daily_task', 'pay', 'bag', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var daily_task_model = player_manager.daily_task;
                var pay_model = player_manager.pay;

                // 是否为至尊卡用户
                if (!pay_model.isExtreme()) {
                    return next(null, {
                        code: Code.MONTHDAY_USER_NOT
                    });
                }

                // 是否领取过
                if (daily_task_model.getScheduleTaskState(daily_task_id) !== 0) {
                    return next(null, {
                        code: Code.TASK_HAVE
                    });
                }

                // 增加至尊卡领取状态
                daily_task_model.addScheduleTaskState(daily_task_id);

                // 发送活跃奖励到玩家背包
                reward_itm = dailyConf.getRewardList(daily_task_id);
                rewardService.addRewardToRole(player_manager, reward_itm, moduleType.MDL_ACT_PERSISTENT_CARD, operationType.OPR_ACT_PERSISTENT_CARD_REWARD);

                // 移除任务
                if (daily_task_model.getScheduleTaskState(daily_task_id) == 1) {
                    daily_task_model.removeTask(daily_task_id);
                }

                // 加入任务id对应活跃度 到数据库
                var add_active = dailyConf.getDailyTaskActive(daily_task_id) || 0;
                daily_task_model.addDailyActive(add_active);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: [reward_itm]
                }
            });
        }
    );
};
